﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace TLWindowsEditorWinFormsDemo
{
    /// <summary>
    /// Xml帮助类
    /// by IT_MAOFY 2024/04/03
    /// </summary>
    public static class XmlHelper
    {
        public static string Serialize<T>(T obj)
        {
            var serializer = new XmlSerializer(typeof(T));
            var namespaces = new XmlSerializerNamespaces();
            namespaces.Add("", ""); // 添加空命名空间，为空表示不使用任何命名空间
            using (MemoryStream ms = new MemoryStream())
            {
                using (XmlWriter xmlWriter = new XmlTextWriterFull(ms, Encoding.UTF8))
                {
                    serializer.Serialize(xmlWriter, obj, namespaces);
                    ms.Position = 0;
                    using (var sr = new StreamReader(ms))
                    {
                        return sr.ReadToEnd();
                    }
                }
            }
        }

        public static T Deserialize<T>(string xml)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (StringReader sr = new StringReader(xml))
            {
                return (T)serializer.Deserialize(sr);
            }
        }

        public static T Deserialize<T>(byte[] xml) 
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (MemoryStream sr = new MemoryStream(xml))
            {
                sr.Position = 0;
                return (T)serializer.Deserialize(sr);
            }
        }
    }

    public class XmlTextWriterFull : XmlTextWriter
    {
        public XmlTextWriterFull(TextWriter w) : base(w) { }

        public XmlTextWriterFull(Stream stream, Encoding enc) : base(stream, enc) { }
        public XmlTextWriterFull(String str, Encoding enc) : base(str, enc) { }


        public override void WriteEndElement()
        {
            base.WriteFullEndElement();
        }
    }
}
